package cn.hongwei.eduservice.controller.admin;

import cn.hongwei.eduservice.entity.Chapter;
import cn.hongwei.eduservice.entity.Video;
import cn.hongwei.eduservice.service.ChapterService;
import cn.hongwei.eduservice.service.VideoService;
import cn.hongwei.result.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Great
 * @email 1224028994@qq.com
 */
@RestController
@CrossOrigin
@RequestMapping("/admin/edu/chapter")
public class AdminChapterController {

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private VideoService videoService;

    //查询指定课程的章和它的小节的嵌套集合
    @GetMapping("getChapters/{courseId}")
    public R getChapters(@PathVariable String courseId){
        //查询章和它的课时集合
        List<Chapter> chapters = chapterService.getChaptersAndVideos(courseId);
        return R.ok().data("items" , chapters);
    }

    //查询指定id的章
    @GetMapping("get/{id}")
    public R getById(@PathVariable String id){
        Chapter chapter = chapterService.getById(id);
        return R.ok().data("item",chapter);
    }

    //保存章节
    @PostMapping("/save")
    public R saveChapter(@RequestBody Chapter chapter){
        chapterService.save(chapter);
        return R.ok();
    }

    //更新章
    @PutMapping("update")
    public R updateById(@RequestBody Chapter chapter){
        chapterService.updateById(chapter);
        return R.ok();
    }

    //删除章
    @DeleteMapping("remove/{id}")
    public R removeChapter(@PathVariable String id){
        //判断如果章有 课时子集合  不能直接删除，必须先删除 课时子集合
        LambdaQueryWrapper<Video> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Video::getChapterId , id);
        int count = videoService.count(wrapper);
        if(count>0){
            return R.error().message("不能删除有课时的章节");
        }
        chapterService.removeById(id);
        return R.ok();
    }
}
